package com.nvyuan.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NioServer {
    //保存客户端连接
   static List<SocketChannel> channelList=new ArrayList<>();

    public static void main(String[] args) throws IOException {
        //创建NI哦 ServerSocketChannel ，与BIO的serverSocket类似
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9000));
        //设置ServerSocketChannel为非堵塞
        serverSocket.configureBlocking(false);
        System.out.println("服务启动成功");
        while (true){
            //非堵塞模式accept方法不会堵塞，否则会堵塞
            //NIO的非堵塞是由操作系统内部实现的，底层采用linux内核的accept
            SocketChannel socketChannel = serverSocket.accept();
            if(socketChannel!=null){
                //如果有客户端进行连接
                System.out.println("连接成功");
                //设置SocketChannel为非堵塞
                socketChannel.configureBlocking(false);
                //保存客户连接在List
                channelList.add(socketChannel);
            }
            //遍历连接进行数据读取
            Iterator<SocketChannel> iterator = channelList.iterator();
            while (iterator.hasNext()){
                SocketChannel sc = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                //非堵塞模式read方法不会堵塞，否则会堵塞
                int len = sc.read(byteBuffer);
                if(len>0){
                    System.out.println("接收到消息"+new String(byteBuffer.array()));

                }else if(len==-1){
                    iterator.remove();
                    System.out.println("客户端断开连接");
                }

            }

        }


    }
}
